package com.hsytech.dijiebao.home.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.hsytech.dijiebao.R;
import com.hsytech.dijiebao.account.SignInActivity;
import com.hsytech.dijiebao.base.BaseActivity;
import com.hsytech.dijiebao.base.BaseApplication;
import com.hsytech.dijiebao.utils.Constants;
import com.hsytech.dijiebao.utils.HttpUtil;
import com.hsytech.dijiebao.utils.SharedPreferencesTools;
import com.hsytech.dijiebao.view.AutoScrollViewPager;
import com.hsytech.dijiebao.view.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.picasso.Picasso;
import com.viewpagerindicator.CirclePageIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;

public class HomeDetailActivity extends BaseActivity {
    private ImageButton top_back_btn;
    private ImageView right_image;
    private CheckBox bar_right_top_btn;
    private TextView bar_title_tv;
    private LinearLayout chart;
    private String ID;
    private TextView create_datetime1, hotel_cat_name1, contact_name1, contact_phone1, start_time1, check_in_num1,
            content1, area_name1;
    private String contact_name, contact_phone;
    private CircleImageView circleImageView;
    private String uid = "", publisher_name = "";
    private Boolean isCollected;
    private DPHttpUtil.HttpCallback callBack = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            JSONObject result = null;
            try {
                result = new JSONObject(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject myData = result.optJSONObject("data");
            String create_datetime = myData.optString("create_datetime");

            contact_name = myData.optString("contact_name");
            contact_phone = myData.optString("contact_phone");

            String start_time = myData.optString("start_time");
            String end_time = myData.optString("end_time");

            String content = myData.optString("content");

            String is_collection = myData.optString("is_collection");
            String head_photo1 = myData.optString("head_photo");
            publisher_name = myData.optString("publisher_name");

            String imgs = myData.optString("imgs");
            uid = myData.optString("uid");
            if (0 == what) {
                // String b = getStringToDate(end_time);
                String hotel_cat_name = myData.optString("hotel_cat_name");
                String check_in_num = myData.optString("check_in_num");
                String area_name = myData.optString("area_name");
                String city_name = myData.optString("city_name");

                start_time1.setText(start_time + "至" + start_time);
                check_in_num1.setText(check_in_num);
                content1.setText(content);
                area_name1.setText(area_name + "  " + city_name);
                hotel_cat_name1.setText(hotel_cat_name);
//
            } else {
                String car_cat_name = myData.optString("car_cat_name");
                String carry_passenger_num = myData.optString("carry_passenger_num");
                String start_place = myData.optString("start_place");
                String end_place = myData.optString("end_place");
                hotel_cat_name1.setText(car_cat_name);

                // String a = getStringToDate(start_time);
                // String b = getStringToDate(end_time);
                start_time1.setText(start_time + "至" + end_time);
                check_in_num1.setText(carry_passenger_num);
                content1.setText(content);
                area_name1.setText(start_place + "至" + end_place);

            }
            Picasso.with(HomeDetailActivity.this).load("http://djb.dev.hsydev.com/Upload/image_sm/" + head_photo1)
                    .into(circleImageView);
            create_datetime1.setText(create_datetime);

            contact_name1.setText(contact_name);
            contact_phone1.setText(contact_phone);

            Log.d("mylog", "��ȡ�ֲ�ͼ" + imgs);
            if (!imgs.equals("[]") && imgs != null) {

                String[] imageUrl = imgs.split(",");
                imageUrls = new String[imageUrl.length];
                imageViewsList = new ArrayList<>();
                for (int i = 0; i < imageUrl.length; i++) {
                    imageUrls[i] = "http://djb.dev.hsydev.com/Upload/image_md/" + imageUrl[i];

                    ImageView view = new ImageView(getApplicationContext());
                    view.setTag(imageUrls[i]);
                    // if (i == 0)// ��һ��Ĭ��ͼ
                    // view.setBackgroundResource(R.drawable.ic_launcher);
                    view.setScaleType(ImageView.ScaleType.FIT_XY);
                    imageViewsList.add(view);
                    Log.d("mylog", imageUrls[i]);
                }

                autoScrollViewPager = (AutoScrollViewPager) findViewById(R.id.autoScrollViewPager);
                previewPagerAdapter = new PreviewPagerAdapter(imageViewsList);
                autoScrollViewPager.setAdapter(previewPagerAdapter);
                Indicator.setViewPager(autoScrollViewPager);
                autoScrollViewPager.setSlideBorderMode(AutoScrollViewPager.SLIDE_BORDER_MODE_NONE);
                autoScrollViewPager.setInterval(3000);
                autoScrollViewPager.startAutoScroll();
            } else {
                autoScrollViewPager_relative.setVisibility(View.GONE);
            }
            BaseApplication.MyDialog.dismiss();
            if (is_collection.equals("1")) {
                right_image.setImageResource(R.mipmap.my_my3);
                isCollected = true;
            } else {
                right_image.setImageResource(R.mipmap.my_my2);
                isCollected = false;
            }
            right_image.setVisibility(View.VISIBLE);
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            BaseApplication.MyDialog.dismiss();
        }
    };
    private DPHttpUtil.HttpCallback collectCallBack = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {

            if (2 == what) {
                showToast("已收藏");
                right_image.setImageResource(R.mipmap.my_my3);
                isCollected = true;
            } else {
                showToast("已取消收藏");
                right_image.setImageResource(R.mipmap.my_my2);
                isCollected = false;
            }
            BaseApplication.MyDialog.dismiss();
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            if (2 == what) {
                showToast("收藏失败");
            } else {
                showToast("取消失败");
            }
            BaseApplication.MyDialog.dismiss();
        }
    };


    private String type;
    private AutoScrollViewPager autoScrollViewPager;
    private PreviewPagerAdapter previewPagerAdapter;
    private String[] imageUrls;
    private List<ImageView> imageViewsList;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private CirclePageIndicator Indicator;
    private RelativeLayout autoScrollViewPager_relative;
    private TextView text_type, text_num;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_home);

        initView();
        getIntentData();
        getHttp();
    }

    private void initView() {
        initTitle();
        initBody();
    }

    private void initBody() {

        autoScrollViewPager_relative = (RelativeLayout) findViewById(R.id.autoScrollViewPager_relative);
        Indicator = (CirclePageIndicator) findViewById(R.id.Indicator);
        circleImageView = (CircleImageView) findViewById(R.id.CircleImageView);
        create_datetime1 = (TextView) findViewById(R.id.create_datetime);
        hotel_cat_name1 = (TextView) findViewById(R.id.hotel_cat_name);
        contact_name1 = (TextView) findViewById(R.id.contact_name);
        contact_phone1 = (TextView) findViewById(R.id.contact_phone);
        start_time1 = (TextView) findViewById(R.id.start_time);
        text_type = (TextView) findViewById(R.id.text_type);
        text_num = (TextView) findViewById(R.id.text_num);

        check_in_num1 = (TextView) findViewById(R.id.check_in_num);
        content1 = (TextView) findViewById(R.id.content);
        area_name1 = (TextView) findViewById(R.id.area_name);
        // ��绰
        contact_phone1.setOnClickListener(new OnClickListener() {
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                // ����һ����ͼ
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact_phone));
                // ��ʼ��ͼ(������绰)
                if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    Activity#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for Activity#requestPermissions for more details.
                    return;
                }
                startActivity(intent);

            }
        });

        // ����
        chart = (LinearLayout) findViewById(R.id.chart);
        chart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (TextUtils.isEmpty(SharedPreferencesTools.getTOKEN(HomeDetailActivity.this))) {
                    showToast(R.string.msg_no_have_token);
                    Intent intent = new Intent(HomeDetailActivity.this, SignInActivity.class);
                    startActivity(intent);
                } else {
                    if (RongIM.getInstance() != null) {
                        /**
                         * �������Ľ��档
                         *
                         * @param context
                         *            Ӧ�������ġ�
                         * @param targetUserId
                         *            Ҫ��֮������û� Id��
                         * @param title
                         *            ����ı��⣬��������ֵ����Ĭ����ʾ��֮������û����ơ�
                         */

                        if (!uid.equals("") && !publisher_name.equals("")) {

                            RongIM.getInstance().startPrivateChat(HomeDetailActivity.this, uid, publisher_name);
                        }

                    }
                }

            }
        });
    }

    private void getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            ID = intent.getStringExtra("id");
            type = intent.getStringExtra("type");

        }
    }

    private void getHttp() {
        BaseApplication.MyDialog.show(this);
        Map<String, String> map = new HashMap<>();
        map.put("id", ID);
        if (!TextUtils.isEmpty(SharedPreferencesTools.getTOKEN(this))) {
            map.put("token", SharedPreferencesTools.getTOKEN(this));
        }
        if ("1".equals(type)) {
            text_type.setText("酒店类型");
            text_num.setText("入住人数");
            HttpUtil.httpPostWithParams(this, 0, Constants.HTTP_HOTLE, map, callBack);
        } else {
            text_type.setText("需求车型");
            text_num.setText("乘车人数");
            HttpUtil.httpPostWithParams(this, 1, Constants.HTTP_TAXI, map, callBack);
        }

    }

    public static String getStringToDate(String time) {
        Date Time = new Date(Long.parseLong(time) * 1000);
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");

        // SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy/MM/dd");

        String retStrFormatNowDate = sdFormatter.format(Time).substring(5);
        return retStrFormatNowDate;
    }

    private void postDelCollectHttp() {
        BaseApplication.MyDialog.show(this);
        Map<String, String> map = new HashMap<>();
        if (!TextUtils.isEmpty(SharedPreferencesTools.getTOKEN(this))) {
            map.put("token", SharedPreferencesTools.getTOKEN(this));
        } else {
            showToast(R.string.msg_no_have_token);
            BaseApplication.MyDialog.dismiss();
            Intent intent = new Intent(HomeDetailActivity.this, SignInActivity.class);
            startActivity(intent);
            return;
        }
        map.put("tid", ID);
        if ("1".equals(type)) {
            map.put("type", "2");
        } else {
            map.put("type", "1");
        }
        HttpUtil.httpPostWithParams(this, 3, Constants.HTTP_DEL_MYSELF, map, collectCallBack);
    }

    private void postCollectHttp() {
        BaseApplication.MyDialog.show(this);
        Map<String, String> map = new HashMap<>();
        if (!TextUtils.isEmpty(SharedPreferencesTools.getTOKEN(this))) {
            map.put("token", SharedPreferencesTools.getTOKEN(this));
        } else {
            showToast(R.string.msg_no_have_token);
            BaseApplication.MyDialog.dismiss();
            Intent intent = new Intent(HomeDetailActivity.this, SignInActivity.class);
            startActivity(intent);
            return;
        }
        map.put("id", ID);
        if ("1".equals(type)) {
            HttpUtil.httpPostWithParams(this, 2, Constants.HTTP_COLLECT_HOTLE, map, collectCallBack);
        } else {
            HttpUtil.httpPostWithParams(this, 2, Constants.HTTP_COLLECT_TAXI, map, collectCallBack);
        }
    }

    private void initTitle() {
        top_back_btn = (ImageButton) findViewById(R.id.top_back_btn);
        top_back_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        right_image = (ImageView) findViewById(R.id.right_image);
        bar_right_top_btn = (CheckBox) findViewById(R.id.bar_right_top_btn);
        bar_title_tv = (TextView) findViewById(R.id.bar_title_tv);
        bar_title_tv.setText("详情");
        right_image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCollected) {
                    postDelCollectHttp();
                } else {
                    postCollectHttp();
                }

            }
        });

    }

    private class PreviewPagerAdapter extends PagerAdapter {

        private List<ImageView> mimageViewsList;
        // private ArrayList<Map<String, String>> mWebSiteUrlList;

        public PreviewPagerAdapter(List<ImageView> imageViewsList) {
            mimageViewsList = imageViewsList;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            // container.removeView(mImageViews[position]);
            container.removeView(mimageViewsList.get(position));
        }

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return super.getItemPosition(object);
        }

        //
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = mimageViewsList.get(position);

            imageLoader.displayImage(imageView.getTag() + "", imageView);

            ((ViewPager) container).addView(mimageViewsList.get(position));
            return mimageViewsList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mimageViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            // TODO Auto-generated method stub
            return view == object;
        }
    }

}
